package inbound

import (
	"fmt"
	"gateway/config"
	"gateway/core"
	"go.uber.org/zap"
)

type httpInbound struct {
	name, path, method string
	args, pathMap      config.Args
	chain              core.Chain
}

func newHttpInbound(name string) core.Inbound {
	return &httpInbound{
		name:    name,
		args:    config.NewArgs(),
		pathMap: config.NewArgs(),
	}
}

func (this *httpInbound) Receive(msg core.Message) bool {
	url, _ := msg.GetContext(HTTP_URL)
	method, _ := msg.GetContext(HTTP_METHOD)
	config.Logger.Debug("Receive request",
		zap.String("url", fmt.Sprintf("%v", url)),
		zap.String("method", fmt.Sprintf("%v", method)))
	if url != this.path {
		return false
	}
	if this.method != "" && this.method != method {
		return false
	}

	this.chain.Dispatch(msg)
	return true
}

func (this *httpInbound) SetArgs(args config.Args) {
	this.args.SetArgs(args)
}

func (this *httpInbound) GetArgs() config.Args {
	return this.args.GetArgs()
}

func (this *httpInbound) Initialize(chain core.Chain) {
	this.path = this.args.GetRequired(PATH)
	this.method = this.args.Get(METHOD)
	this.chain = chain
	config.Logger.Info("Initialize HttpInbound",
		zap.String("name", this.name),
		zap.String("path", this.path),
		zap.String("method", this.method))
}

func (this *httpInbound) Destroy() {
	config.Logger.Info("Destroy HttpInbound", zap.String("name", this.name))
}
